<template>
  <div :id="smallType ? 'smallType' : 'largeType'" ref="attrTable" class="v-attrTable">
    <div class="g-jc-sb _header g-flex-0">
      <div class="g-ai-c">
        <img :src="selectedElement && selectedElement.iconPath" alt="" style="margin-right: 4px">
        <span style="font-size:12px; color: #000">
          {{type}}
        </span>
      </div>
      <div class="g-ai-c _button-area">
        <a-button 
          :disabled="selectedElement && selectedElement.disabled"
          class="g-ai-c addButton" 
          @click="showMenu = true" 
          @blur="showMenu = false">
          <img src='statics/icons/table/iconadd2.svg' width="14px"/>
          <div v-show="showMenu" class="_menu-area">
            <m-menu :menu="menuList" @click-menu-item="handleClickMenuItem"/>
          </div>
        </a-button>
        <div class="divider"></div>
        <a-button :disabled="selectedRowKeys.length === 0" class="g-ai-c" @click="removeNode">
          <img src='statics/icons/table/toolbardelete.svg' width="14px"/>
        </a-button>
        <div class="divider"></div>
        <span class="_sort _img-btn" :class="{'_sort-active':sortActive}" @click="handleSort">
          <img src='statics/icons/app/textsort.png'/>
        </span>
      </div>
    </div>
    <main>
      <a-table
        v-show="tableData.length > 0"
        class="_table-area"
        rowKey="id"
        :columns="sortColumns"
        :scroll="{ x: scrollX, y: scrollY }"
        :style="{width: '100%'}"
        :customRow="customRow"
        :data-source="tableData"
        :pagination="false"
        :bordered="true">
        <!-- <template slot="properties" slot-scope="text, record, index">
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, getCheckboxProps: getCheckboxProps}"
          <m-property
            :property="text[index]"
            :graphNode="record.graphNode"
            :isPropertyGroup="true"
          />
        </template> -->
      </a-table>
    </main>
  </div>
</template>
<script>
import Menu from 'src/components/common/ContextMenu/Menu.vue';
import Property from './Property';
import { PropertyUtil } from './PropertyUtil';
import { graphHelper } from 'src/api/GraphHelper';
import { SysMLUtilHelper } from "src/api/sysml-imports";
import { actions, OpenCreateElementAction } from '@/pages/mxgraph/Actions';

export default {
  name: 'attr-table',
  components: {
    'm-menu': Menu,
    'm-property': Property
  },
  props: {
    propertyGroupConfig: Object,
    property: Object, //// 当前选中元素的property
    smallType: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      columns: [],
      menuList: [],
      sortActive: false,
      tableData: [],
      cacheTableData: [], //// 防止row-selection设置后报错
      showMenu: false,
      propertiesObj: null,
      scrollX: 0,
      scrollY: 330,
      type: '',
      selectedRowId: '',
      selectedRowKeys: [],
      modules: [],
      isAdd: false,
      graphNodes: [], //// 存储每行信息对应的graphNode
      rows: null, //// 行所在的dom列表
    };
  },
  computed: {
    selectedElement(){
      return app.selectedElement;
    },
    value(){
      return PropertyUtil.getNodePropertyValue(this.selectedElement, this.property);
    },
    sortColumns() {
      let columns = [...this.columns];
      if (this.sortActive) {
        columns.sort((a, b) => ('' + a.title).localeCompare(b.title));
      }
      return columns;
    }
  },
  watch: {
    propertyGroupConfig: function () {
      this.initData();
      this.initClickEvent();
    },
    value: function (newVal, oldVal) {
      this.getColumns();
    },
    selectedElement: {
      handler(val){
        if (val) {
          const type = val.getTypeName();
          this.type = app.activeProject.configManager.getTypeNameConfig()[type]?.cnName || '';
        }
      },
      immediate: true
    }
  },
  created() {
    this.initData();
  },
  mounted() {
    if (this.smallType) {
      const tableDom = document.querySelector('.v-workspace-attribute .ant-tabs-content');
      this.scrollY = tableDom.offsetHeight - 28 - 23;
    }
    this.initClickEvent();
  },
  methods: {
    //// 获取列数据和行数据
    getColumns() {
      console.log('触发了getColumns');
      const propertyColumns = this.propertyGroupConfig.columns;
      const modules = app.selectedElement.model[this.propertyGroupConfig.propertyKey] ? 
        app.selectedElement.model[this.propertyGroupConfig.propertyKey]().toArray() : [];
      const data = [];
      const cacheTableData = [];
      const columns = [];
      let scrollX = 0;
      console.log('modules', modules);
      const graphNodes = [];
      modules.forEach(model => {
        const dataItem = {};
        const cacheDataItem = {};
        const graphNode = graphHelper.getGraphNodeById(model.id, app.activeProjectId);
        if (!graphNode) return;
        graphNodes.push(graphNode);
        const properties = graphNode.properties.toArray();
        this.initProperty(graphNode, properties);

        dataItem.id = model.id;
        dataItem.key = model.id;
        cacheDataItem.graphNode = graphNode;
        cacheDataItem.id = model.id;
        dataItem.properties = [];
        cacheDataItem.properties = [];
        scrollX = 0;
        propertyColumns.forEach((item, index) => {
          const column = {};
          column.title = item.name;
          column.key = item.id;
          column.dataIndex = 'properties';
          scrollX += 140;
          if (index < propertyColumns.length - 1) {
            column.width = 140;
          }
          column.customRender = this.customRender(index);
          column.ellipsis = true;
          item.scopedSlots = { customRender: 'properties' };
          cacheDataItem.properties.push(properties[this.propertiesObj[item.name]]);
          columns[index] = column;
        });
        data.push(dataItem);
        cacheTableData.push(cacheDataItem);
      });
      //// console.log(columns, data, cacheTableData);
      this.modules = modules;
      this.graphNodes = graphNodes;
      this.cacheTableData = cacheTableData;
      this.columns = columns;
      this.tableData = data;
      this.scrollX = scrollX + 50;
      this.$nextTick(this.setScrollBarStyle);
    },

    //// 初始化信息
    initData() {
      this.modules = [];
      this.graphNodes = [];
      this.cacheTableData = [];
      this.columns = [];
      this.tableData = [];
      this.scrollX = 90;
      this.menuList = [];
      this.sortActive = false;
      this.propertiesObj = null;
      this.selectedRowId = '';
      this.selectedRowKeys = [];
      if (!this.propertyGroupConfig.propertyKey) return;
      this.getColumns();
      this.getCreateElementMenu();
    },

    //// 获取创建元素的菜单
    getCreateElementMenu() {
      //// 获取选中节点与当前属性对应的property,获取moreBtnCondition
      const selectedElement = app.selectedElement;
      const selectedElementProperties = selectedElement.properties.toArray();
      let moreBtnCondition = this.property.config.moreBtnCondition;
      const typeName = SysMLUtilHelper.getTypeNameByClassType(moreBtnCondition, app.activeProjectId);
      
      //// const list = app.activeProject.configManager.getNestConfig()[typeName];
      const typeNameConfig = app.activeProject.configManager.getTypeNameConfig();
      const list = typeName.map(item => typeNameConfig[item]);
      const ownerConfig = app.activeProject.configManager.getOwnerConfig();
      //// console.log('typeName', typeName, list, typeNameConfig, ownerConfig);
      if (!list) return;
      const menuList = [];
      list.forEach(item => {
        if (ownerConfig[item.typeName] && ownerConfig[item.typeName].menu) {
          menuList.push(app.activeProject.configManager.getTreeNodeByTypeName(item.typeName));
        }
      });
      //// console.log('list', list, menuList);
      this.menuList = menuList;
    },

    //// 设置滚动条样式
    setScrollBarStyle() {
      const table = this.$refs.attrTable;
      const tableBody = table.querySelector('.ant-table-body');
      const tableHeader = table.querySelector('.ant-table-header');
      const height = tableBody.offsetHeight;
      //// console.log('height', height, this.scrollY, tableBody);
      if (height >= this.scrollY) {
        tableHeader.style.marginRight = '0';
      } else {
        tableHeader.style.marginRight = '-12px';
      }
      if (this.isAdd) {
        tableBody.scrollTop = table.querySelector('.ant-table-tbody').offsetHeight; //// 滚到最底部
      }
    },

    customRender(colIndex) {
      return (text, record, index) => {
        return <m-property
          property={this.cacheTableData[index]['properties'][colIndex]}
          graphNode={this.cacheTableData[index]['graphNode']}
          isPropertyGroup={true}
          selectedRowId={this.selectedRowId}
          onSelect={this.handleSelectRow}
        />;
      };
    },

    initProperty(graphNode, properties) {
      if (this.propertiesObj) return;
      const propertiesObj = {};
      properties.forEach((item, index) => {
        propertiesObj[item.config.name] = index;
      });
      this.propertiesObj = propertiesObj;
      //// console.log('this.propertiesObj ', this.propertiesObj );
    },

    handleSort() {
      this.sortActive = !this.sortActive;
    },

    onSelectChange(selectedRowKeys) {
      //// console.log('selectedRowKeys changed: ', selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
    },

    handleSelectRow(row, graphNode){
      //// console.log('select', row);
      this.selectedRowId = graphNode.id + row.config.key;
    },

    //// 移除节点
    removeNode() {
      const idSet = new Set([...this.selectedRowKeys]);
      this.selectedRowKeys.forEach(id => {
        const graphNode = graphHelper.getGraphNodeById(id, app.activeProjectId);
        graphNode.remove();
      });
      //// this.modules = this.modules.filter(data => !idSet.has(data.id));
      //// this.graphNodes = this.graphNodes.filter(data => !idSet.has(data.id));
      this.isAdd = false;
      PropertyUtil.updateRow(this.modules.filter(data => !idSet.has(data.id)), this.property, this.selectedElement, this.graphNodes);
      //// this.tableData = this.tableData.filter(data => !idSet.has(data.id));
      //// this.cacheTableData = this.cacheTableData.filter(data => !idSet.has(data.id));
      this.selectedRowKeys = [];
      //// this.$nextTick(this.setScrollBarStyle);
    },

    getCheckboxProps(record, index) {
      const disabled = graphHelper.getGraphNodeById(record.id, app.activeProjectId).disabled;
      return {
        props: {
          disabled: disabled, //// Column configuration not to be checked
        },
      };
    },

    handleClickMenuItem(menuItem) {
      const openCreateElementAction = new OpenCreateElementAction();
      const newGraphNode = openCreateElementAction.run(this.selectedElement, menuItem);
      this.isAdd = true;
      PropertyUtil.updateRow([...this.modules, newGraphNode.model], this.property, this.selectedElement, [...this.graphNodes, newGraphNode]);
      //// this.getColumns();
    },

    //// 自定义行
    customRow(record) {
      //// console.log(record, 'record');
      const graphNode = graphHelper.getGraphNodeById(record.id, app.activeProjectId);
      return {
        on: {
          click: (event) => {
            if (graphNode.disabled) return; 
            const target = this.findTarget(event.target);
            this.removeSelected();
            target.classList.add('selected');
            this.selectedRowKeys = [record.id];
          },
        }
      };
    },

    findTarget(currentDom) {
      if (currentDom.classList.contains('ant-table-row')) {
        return currentDom;
      } else {
        return this.findTarget(currentDom.parentElement);
      }
    },

    //// 重置点击后的选中效果，点击行以外的地方取消选中
    initClickEvent() {
      const table = this.$refs.attrTable;
      const tableArea = table.querySelector('._table-area');
      const main = table.querySelector('main');
      this.removeSelected();
      this.selectedRowKeys = [];
      tableArea.onclick = function (e) {
        e.stopPropagation();
      };
      main.onclick = () => {
        this.removeSelected();
        this.selectedRowKeys = [];
      };
    },

    //// 移除选中效果
    removeSelected() {
      const table = this.$refs.attrTable;
      const tableBody = table.querySelector('.ant-table-tbody');
      const rows = tableBody.querySelectorAll('.ant-table-row');
      for (let i = 0; i < rows.length; i++) {
        const row = rows[i];
        row.classList.remove('selected');
      }
    }
  }
};
</script>
<style lang="scss">
.v-attrTable {
  height: 100%;
  padding: 8px;
  ._list-content.readOnlyAttr {
    cursor: not-allowed;
    ._row{
      pointer-events: none;
    }
  }
	._row {
		line-height: 20px;
    ._readonly{
      color: rgba(0,0,0,.45);
    }
		._col-label {
			line-height: 20px;
			flex: 0 0 96px;
			width: 96px;
			border-right: 1px solid #eee;
			color: black;
			padding: 5px;
			font-size: 12px;
		}
		._col-value {
			line-height: 20px;
			flex:1 1 100px;
			width: 100px;
			padding: 5px;
      border: 1px solid transparent;
		}
		&._selected {
			._col-label {
				background: #3483b8;
				//// border-right: 1px solid #3483b8;
				color: white;
			}
      ._col-value{
        box-sizing: border-box;
        border: 1px solid #1890FF;
      }

		}
  }
._header {
		padding:4px 10px ;
    background:#D4EBF8;
    border-left: 1px solid #E4E3E3;
    border-right: 1px solid #E4E3E3;
    border-top: 1px solid #E4E3E3;
    height: 31px;
    .divider {
      width: 1px;
      height: 16px;
      background: #B1CEE2;
      margin: 0 10px;
    }
    ._button-area {     
      button {
        padding: 0;
        border: 0;
        background: #D4EBF8;
        height: 18px;
        width: 18px;
        text-align: center;
        display: flex;
        justify-content: center;
        &::after {
          animation: unset;
        }
      }
      
      .addButton {
        position: relative;
        ._menu-area {
          width: 125px;
          position: absolute;
          left: -20px;
          top: 23px;
          z-index: 100;
          ._menu-item > ._right-cell {
            min-width: unset;
            text-align: left;
          }
      }
      }
    }
	}
	._sort {
    border: 1px solid #D4EBF8;
    vertical-align: middle;
		&._sort-active {
		  background: linear-gradient(180deg, #B9E3FF 0%, #47B3FF 55%, #80C8FE 100%);
      border: 1px solid #B1CEE2;
		}
	}
	._img-btn {
		display: inline-block;
		box-sizing: border-box;
		cursor: pointer;
		img {
			display: block;
			height: 14px;
			width: 14px;
		}
		&:hover {
      background: linear-gradient(180deg, #E7F5FE 0%, #B0DEFF 65%, #B2DDFD 100%);
      border: 1px solid #B1CEE2;
		}
		&:active {
      background: linear-gradient(180deg, #B9E3FF 0%, #47B3FF 55%, #80C8FE 100%);
      border: 1px solid #B1CEE2;
		}
  }
  main {
    height: calc(100% - 45px);
    ._table-area {
      .ant-table-header {
        //// overflow: unset !important;
        table {
          border-radius: 0;
        }
        &::-webkit-scrollbar {
          border: 0 !important;
        }
        th {
          &:last-of-type {
            border-right-color: #E4E3E3 !important;
          }
        }
      }
      .hide-row {
        display: none;
      }
      .ant-table-body {
        overflow-y: auto !important;
        overflow-x: auto !important;
        &::-webkit-scrollbar {
          width: 12px;
        }
      }
      table {
        border-top: 0;
        border-color: #E4E3E3;
        font-size: 12px;
      }
      tr {
        &:hover {
          td {
            background-color: #fff !important;
          }
        }
        &.selected {
          td {
            background-color: #3483B8 !important;
          }
        }
      }
      tr th {
        padding: 5px 10px;
        //// background: linear-gradient(180deg, #DAF0FC 0%, #FAFDFF 100%);
        border-color: #E4E3E3;
      }
      tr td {
        padding: 1px 10px;
        border-color: #E4E3E3;
        border-radius: 0;
      }
      ._col-value {
        padding: 0;
        height: 22px;
        ._img-btn {
          top: 2px !important;
        }
      }
      .ant-select-selection--single {
        height: 20px;
        .ant-select-selection__rendered {
          line-height: 18px;
        }
      }
      .v-simple-input {
        height: 20px !important;
        min-height: 20px !important; 
      }
      .v-attr-compounded-input {
        height: 20px;
        line-height: 20px;
        .ant-input-sm {
          height: 20px;
        }
      }
      .v-simple-input {
        height: 20px;
        padding-bottom: 0;
        padding-top: 0;
        min-height: 20px;
      }
    }
  }
  &#smallType {
    background-color: #fff;
    padding: 0;
    ._header {
      position: relative;
      z-index: 1;
      height: 30px;
      background: #D4EBF8;
      border: 0;
      border-bottom: 1px solid #B1CEE2;     
      ._sort {
        border-color: #D4EBF8;
      }
      ._button-area {
        button {
          padding: 0;
          border: 0;
          background: #D4EBF8;
          img {
            margin-right: 0;
          }
        }
        ._menu-area {
          left: -76px;
        }
      }
    }
    main {
      margin: 0;
      margin-top: -1px;
      height: calc(100% - 30px);
      ._table-area {
        th, td {
          border-color: #F0F0F0;
        }
        tr, th {
          padding-top: 2px;
          padding-bottom: 2px;
        }
      }
    }
  }
}
</style>
